<template>
  <div class="flow-container">
    <div class="forum-home-container">
      <aside class="forum-sidebar">
        <button class="create-post-btn" @click="goToCreate">
          <el-icon class="btn-icon"><EditPen /></el-icon>
          发布新帖
        </button>
        <h3>
          <el-icon class="section-icon"><Collection /></el-icon>
          帖子分类
        </h3>
        <ul>
          <li v-for="cat in categories" :key="cat.id" :class="{active: cat.id === selectedCategory.id}" @click="selectCategory(cat)">
            <el-icon class="category-icon">
              <Folder v-if="cat.id === -1" />
              <Document v-else />
            </el-icon>
            {{ cat.name }}
          </li>
        </ul>
        
        <!-- 新增快捷功能区域 -->
        <div class="quick-actions">
          <h4>
            <el-icon class="actions-icon"><Operation /></el-icon>
            快捷操作
          </h4>
          <div class="action-item" @click="goToMyPosts">
            <el-icon class="action-icon"><UserFilled /></el-icon>
            我的帖子
          </div>
          <div class="action-item" @click="goToFavorites">
            <el-icon class="action-icon"><Star /></el-icon>
            我的收藏
          </div>
          <div class="action-item" @click="goToMessages">
            <el-icon class="action-icon"><Message /></el-icon>
            消息通知
          </div>
        </div>
      </aside>
      <main class="forum-main">
        <div class="forum-header">
          <div class="forum-title">
            <el-icon class="title-icon"><School /></el-icon>
            CLASSTOPIA
            <div class="title-subtitle">智慧学习社区</div>
          </div>
          <div class="welcome-banner">
            <el-icon class="banner-icon"><Sunny /></el-icon>
            <span>欢迎来到课托邦，与同学们一起分享知识，共同成长！</span>
          </div>
        </div>
        
        <div class="search-wrapper">
          <div class="search-container">
            <el-icon class="search-icon"><Search /></el-icon>
            <input
              v-model="searchKeyword"
              type="text"
              class="search-input"
              placeholder="搜索帖子、用户或话题..."
              @keyup.enter="onSearch"
            />
            <button class="search-btn" @click="onSearch">
              <el-icon class="btn-search-icon"><Search /></el-icon>
              搜索
            </button>
          </div>
        </div>
        
        <div class="divider"></div>
        
        <div class="post-section">
          <div class="post-tabs">
            <button :class="{active: postViewMode==='latest'}" @click="changeViewMode('latest')">
              <el-icon class="tab-icon"><Clock /></el-icon>
              最新
            </button>
            <button :class="{active: postViewMode==='hot'}" @click="changeViewMode('hot')">
              <el-icon class="tab-icon"><MoreFilled /></el-icon>
              最多点赞
            </button>
          </div>
          <div class="post-list">
            <div v-if="loading" class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              加载中...
            </div>
            <div v-else-if="filteredPosts.length === 0" class="empty-state">
              <el-icon class="empty-icon"><Document /></el-icon>
              <p>暂无帖子</p>
              <p class="empty-subtitle">成为第一个发帖的人吧！</p>
            </div>
            <template v-else>
              <div v-for="post in filteredPosts" :key="post.id" class="post-item-link" @click="goToPost(post.id)" style="text-decoration:none; cursor:pointer;">
                <div class="post-item">
                  <div class="post-badge">
                    <el-icon class="badge-icon"><ChatDotRound /></el-icon>
                  </div>
                  <div class="post-item-layout">
                    <h4 class="post-title">{{ post.title }}</h4>
                    <p class="post-content">{{ post.content }}</p>
                    <div class="post-meta">
                      <div class="meta-item">
                        <el-icon class="meta-icon"><User /></el-icon>
                        <span>{{ post.author }}</span>
                      </div>
                      <div class="meta-item">
                        <el-icon class="meta-icon"><Star /></el-icon>
                        <span>{{ post.likes }}</span>
                      </div>
                      <div class="meta-item">
                        <el-icon class="meta-icon"><Clock /></el-icon>
                        <span>{{ post.time }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
          <div class="pagination-bar">
            <button :disabled="currentPage===1 || loading" @click="loadPage(currentPage-1)">
              <el-icon class="pagination-icon"><ArrowLeft /></el-icon>
              上一页
            </button>
            <span class="page-info">
              <el-icon class="page-icon"><Document /></el-icon>
              第 {{ currentPage }} / {{ totalPages }} 页
            </span>
            <button :disabled="currentPage===totalPages || loading" @click="loadPage(currentPage+1)">
              下一页
              <el-icon class="pagination-icon"><ArrowRight /></el-icon>
            </button>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useForumStore } from '../../stores/forum'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { getPosts } from '@/api/forum' // 1. 引入 getPosts
import { getAllCategories } from '@/api/category' // 新增
import { 
  EditPen, Collection, Folder, Document, DataAnalysis, User, ChatDotRound, 
  Star, Operation, UserFilled, Message, School, Sunny, Search, Clock, 
  MoreFilled, Loading, ArrowLeft, ArrowRight 
} from '@element-plus/icons-vue'

const router = useRouter()
const forumStore = useForumStore()
const { posts: storePosts, loading } = storeToRefs(forumStore)

const categories = ref<{ id: number; name: string }[]>([{ id: -1, name: '全部' }])
const selectedCategory = ref<{ id: number; name: string }>(categories.value[0])
const postViewMode = ref<'latest'|'hot'>('latest')
const searchKeyword = ref('')
const pageSize = 10
const currentPage = ref(1)
const totalPages = ref(1)

// 新增统计数据
const onlineUsers = ref(Math.floor(Math.random() * 100) + 50)
const todayPosts = ref(Math.floor(Math.random() * 20) + 10)
const featuredPosts = ref(Math.floor(Math.random() * 15) + 5)

// 首次加载
onMounted(() => {
  loadCategories()
})

// 监听筛选条件变化自动刷新第一页
watch([selectedCategory, postViewMode], () => {
  loadPage(1)
})

async function loadPage(page: number) {
  if (page < 1) page = 1
  currentPage.value = page
  const params: any = { page, size: pageSize }
  if (selectedCategory.value.id !== -1) {
    params.categoryId = selectedCategory.value.id
  }
  const res = await forumStore.fetchPosts(params.page, params.size, params.categoryId)
  totalPages.value = (res && typeof res.totalPages === 'number') ? res.totalPages : 1
}

async function loadCategories() {
  try {
    const res = await getAllCategories()
    const list = Array.isArray(res) ? res : (res.data || [])
    categories.value = [{ id: -1, name: '全部' }, ...list.map((c: any) => ({ id: c.id, name: c.name }))
    ]
    selectedCategory.value = categories.value[0]
    loadPage(1)
  } catch (e) {
    categories.value = [{ id: -1, name: '全部' }]
    selectedCategory.value = categories.value[0]
    loadPage(1)
  }
}

const filteredPosts = computed(() => {
  let filtered = storePosts.value || []
  if (searchKeyword.value.trim()) {
    const kw = searchKeyword.value.trim()
    filtered = filtered.filter(p =>
      (p.title && p.title.includes(kw)) ||
      (p.content && p.content.includes(kw)) ||
      (p.author && p.author.includes(kw))
    )
  }
  if (postViewMode.value === 'hot') {
    filtered = [...filtered].sort((a, b) => (b.likes || 0) - (a.likes || 0))
  } else {
    filtered = [...filtered].sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime())
  }
  return filtered
})

function selectCategory(cat: { id: number; name: string }) {
  selectedCategory.value = cat
  loadPage(1)
}

function changeViewMode(mode: 'latest'|'hot') {
  postViewMode.value = mode
}

function goToCreate() {
  router.push('/forum-create')
}

function goToPost(postId: number) {
  router.push(`/forum/${postId}`)
}

async function onSearch() {
  console.log('onSearch called, keyword:', searchKeyword.value)
  await forumStore.fetchPosts(currentPage.value, pageSize)
}

// 新增快捷操作函数
function goToMyPosts() {
  router.push('/my-posts')
}

function goToFavorites() {
  router.push('/favorites')
}

function goToMessages() {
  router.push('/message')
}
</script>

<style scoped>
.forum-home-container {
  display: flex;
  gap: 24px;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  background: transparent;
  width:100%;
}

.forum-sidebar {
  flex: 0 0 180px;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20px);
  border-radius: var(--radius-xl);
  padding: 28px;
  height: fit-content;
  position: sticky;
  top: 0px;
  box-shadow: var(--shadow-purple);
  border: 1px solid rgba(162, 89, 236, 0.15);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.forum-sidebar:hover {
  box-shadow: 0 8px 40px rgba(162, 89, 236, 0.2), 0 4px 16px rgba(162, 89, 236, 0.15);
  transform: translateY(-4px);
  border-color: rgba(162, 89, 236, 0.25);
}

.forum-sidebar h3 {
  color: var(--primary-purple);
  font-size: 18px;
  font-weight: 700;
  margin: 0 0 20px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid var(--light-purple);
  position: relative;
}

.forum-sidebar h3::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 40px;
  height: 2px;
  background: var(--gradient-purple);
  border-radius: 2px;
}

.forum-sidebar ul {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}

.forum-sidebar li {
  padding: 14px 18px;
  margin: 6px 0;
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: var(--text-secondary);
  font-weight: 500;
  text-align: center;
  position: relative;
  overflow: hidden;
}

.forum-sidebar li:hover {
  background: linear-gradient(135deg, rgba(162, 89, 236, 0.1) 0%, rgba(91, 110, 225, 0.1) 100%);
  color: var(--primary-purple);
  transform: translateX(4px);
}

.forum-sidebar li.active {
  background: var(--gradient-purple);
  color: white;
  box-shadow: var(--shadow-purple);
}

.forum-main {
  flex: 1;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20px);
  border-radius: var(--radius-xl);
  padding: 36px;
  box-shadow: var(--shadow-blue);
  border: 1px solid rgba(91, 110, 225, 0.15);
}

.forum-header {
  margin-bottom: 32px;
}

.forum-title {
  font-size: 2.5rem;
  font-weight: 700;
  text-align: center;
  background: var(--gradient-purple);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 16px;
  letter-spacing: 1px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.title-icon {
  font-size: 2.5rem;
  color: var(--primary-purple);
}

.title-subtitle {
  font-size: 1rem;
  color: var(--text-muted);
  font-weight: 400;
  margin-top: 8px;
  letter-spacing: 0.5px;
}

.welcome-banner {
  background: linear-gradient(135deg, rgba(162, 89, 236, 0.1) 0%, rgba(91, 110, 225, 0.1) 100%);
  padding: 16px 24px;
  border-radius: var(--radius-lg);
  text-align: center;
  color: var(--text-secondary);
  font-size: 14px;
  border: 1px solid rgba(162, 89, 236, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.banner-icon {
  font-size: 18px;
  color: var(--primary-blue);
}

.search-wrapper {
  display: flex;
  gap: 16px;
  margin-bottom: 32px;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.search-container {
  position: relative;
  flex: 1;
  width:98%;
  display: flex;
  align-items: center;
}

.search-icon {
  position: absolute;
  left: 20px;
  font-size: 18px;
  color: var(--text-muted);
  z-index: 2;
}

.search-input {
  width: 100%;
  height: 52px;
  border: 2px solid var(--border-light);
  border-radius: var(--radius-xl);
  padding: 0 24px 0 50px;
  font-size: 16px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: rgba(255, 255, 255, 0.9);
  outline: none;
  color: var(--text-primary);
}

.search-input:focus {
  border-color: var(--primary-blue);
  box-shadow: 0 0 0 4px rgba(91, 110, 225, 0.1);
  background: white;
  padding-left: 50px;
}

.search-btn {
  height: 52px;
  padding: 0 28px;
  background: var(--gradient-blue);
  color: white;
  border: none;
  border-radius: var(--radius-xl);
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: var(--shadow-blue);
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 12px;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 32px rgba(91, 110, 225, 0.25);
}

.btn-search-icon {
  font-size: 16px;
}

.post-section {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 0;
}

.post-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 24px;
  justify-content: center;
}

.post-tabs button {
  padding: 14px 28px;
  border: 2px solid var(--border-medium);
  border-radius: var(--radius-lg);
  background: transparent;
  color: var(--text-secondary);
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  outline: none;
  box-shadow: var(--shadow-sm);
  display: flex;
  align-items: center;
  gap: 8px;
}

.post-tabs button:hover {
  border-color: var(--primary-blue);
  color: var(--primary-blue);
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.post-tabs button.active {
  background: var(--gradient-blue);
  color: white;
  border-color: transparent;
  box-shadow: var(--shadow-blue);
}

.tab-icon {
  font-size: 16px;
}

/* 加载和空状态样式 */
.loading-state, .empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-muted);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.loading-icon, .empty-icon {
  font-size: 48px;
  color: var(--primary-purple);
  margin-bottom: 8px;
}

.loading-icon {
  animation: spin 2s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.empty-state p {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-secondary);
}

.empty-subtitle {
  font-size: 14px !important;
  font-weight: 400 !important;
  color: var(--text-muted) !important;
}

.post-item {
  background: rgba(255, 255, 255, 0.95);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-light);
  padding: 28px;
  position: relative;
  min-height: 140px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  overflow: hidden;
  margin:20px 0;
}

.post-badge {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: var(--gradient-purple);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.8;
}

.badge-icon {
  font-size: 18px;
  color: white;
}

.post-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: var(--gradient-purple);
  transform: scaleX(0);
  transition: transform 0.4s ease;
}

.post-item:hover::before {
  transform: scaleX(1);
}

.post-item:hover {
  box-shadow: var(--shadow-purple);
  background: rgba(252, 250, 255, 0.98);
  transform: translateY(-6px);
  border-color: var(--light-purple);
}

.post-item:hover .post-badge {
  transform: scale(1.1);
  opacity: 1;
}

.post-item:active {
  transform: translateY(-3px);
  box-shadow: var(--shadow-lg);
}

.post-item-layout {
  display: flex;
  flex-direction: column;
  gap: 12px;
  height: 100%;
  margin-right: 50px;
}

.post-title {
  font-size: 20px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0;
  line-height: 1.4;
  transition: color 0.3s ease;
}

.post-item:hover .post-title {
  color: var(--primary-purple);
}

.post-content {
  color: var(--text-secondary);
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
  flex: 1;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.post-meta {
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: var(--text-muted);
  align-items: center;
  margin-top: auto;
  padding-top: 16px;
  border-top: 1px solid var(--border-light);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-icon {
  font-size: 14px;
  color: var(--primary-blue);
}

.divider {
  width: 100%;
  height: 4px;
  background: var(--gradient-purple);
  margin: 40px 0;
  border-radius: var(--radius-sm);
  box-shadow: var(--shadow-sm);
}

.create-post-btn {
  width: 100%;
  height: 52px;
  margin-bottom: 28px;
  background: var(--gradient-purple);
  color: white;
  border: none;
  border-radius: var(--radius-xl);
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: var(--shadow-purple);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.create-post-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 32px rgba(162, 89, 236, 0.3);
}

.btn-icon {
  font-size: 18px;
}

.forum-sidebar h3 {
  color: var(--primary-purple);
  font-size: 18px;
  font-weight: 700;
  margin: 0 0 20px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid var(--light-purple);
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-icon {
  font-size: 20px;
  color: var(--primary-purple);
}

.forum-sidebar li {
  padding: 14px 18px;
  margin: 6px 0;
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: var(--text-secondary);
  font-weight: 500;
  text-align: left;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  gap: 10px;
}

.category-icon {
  font-size: 16px;
  color: var(--primary-blue);
}

/* 新增统计信息样式 */
.forum-stats {
  margin-top: 32px;
  padding: 20px;
  background: linear-gradient(135deg, rgba(162, 89, 236, 0.08) 0%, rgba(91, 110, 225, 0.08) 100%);
  border-radius: var(--radius-lg);
  border: 1px solid rgba(162, 89, 236, 0.15);
}

.forum-stats h4 {
  margin: 0 0 16px 0;
  color: var(--primary-purple);
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.stats-icon {
  font-size: 18px;
  color: var(--primary-purple);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  padding: 8px 0;
}

.stat-icon {
  font-size: 16px;
  color: var(--primary-blue);
}

.stat-label {
  flex: 1;
  font-size: 14px;
  color: var(--text-secondary);
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
  color: var(--primary-purple);
}

/* 新增快捷操作样式 */
.quick-actions {
  margin-top: 24px;
  padding: 20px;
  background: linear-gradient(135deg, rgba(91, 110, 225, 0.08) 0%, rgba(162, 89, 236, 0.08) 100%);
  border-radius: var(--radius-lg);
  border: 1px solid rgba(91, 110, 225, 0.15);
}

.quick-actions h4 {
  margin: 0 0 16px 0;
  color: var(--primary-blue);
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.actions-icon {
  font-size: 18px;
  color: var(--primary-blue);
}

.action-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 16px;
  margin: 8px 0;
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all 0.3s ease;
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 500;
}

.action-item:hover {
  background: rgba(255, 255, 255, 0.6);
  color: var(--primary-blue);
  transform: translateX(4px);
}

.action-icon {
  font-size: 16px;
  color: var(--primary-blue);
}

.pagination-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 40px;
  padding: 28px 0;
  border-top: 1px solid var(--border-light);
}

.pagination-bar button {
  background: var(--gradient-blue);
  color: white;
  border: none;
  border-radius: var(--radius-lg);
  padding: 14px 24px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: var(--shadow-sm);
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-bar button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: var(--shadow-blue);
}

.pagination-bar button:disabled {
  background: var(--text-light);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.pagination-icon {
  font-size: 14px;
}

.page-info {
  font-size: 14px;
  color: var(--text-primary);
  font-weight: 500;
  padding: 0 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-icon {
  font-size: 16px;
  color: var(--primary-purple);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .forum-home-container {
    flex-direction: column;
    gap: 20px;
  }
  
  .forum-sidebar {
    flex: none;
    position: static;
  }
  
  .forum-main {
    padding: 24px;
  }
}

@media (max-width: 768px) {
  .forum-home-container {
    padding: 0 12px;
  }
  
  .forum-title {
    font-size: 2rem;
  }
  
  .search-wrapper {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-input {
    max-width: none;
  }
  
  .post-item {
    padding: 20px;
  }
  
  .post-tabs {
    flex-direction: column;
    gap: 8px;
  }
  
  .post-tabs button {
    padding: 10px 20px;
  }
}
</style>
